<template>
  <div class="order-index">
    <OrderStatusNav @click="selectStatus" :orderStatusNav="orderStatusNav"></OrderStatusNav>
    <div class="order-main">
        <div class="head">
            <div class="number">
                <span>订单号：</span>
                <el-input @clear="getOrder()" :clearable="true" v-model="number" placeholder="请填写订单号"></el-input>
            </div>
            <div class="phone">
                <span>手机号：</span>
                <el-input @clear="getOrder()" :clearable="true" v-model="phone" placeholder="请填写手机号"></el-input>
            </div>
            <div class="order-time">
                <span>下单时间：</span>
                <el-date-picker
                 :clearable="true"
                 range-separator="至"
                 start-placeholder="开始日期"
                 end-placeholder="结束日期"
                 type="daterange"
                 :default-time="['00:00:00', '23:59:59']"
                 v-model="orderDate"
                 @change="confirmDate"></el-date-picker>
            </div>
            <div class="btn" @click="handleSearch">查询</div>
        </div>
        <div v-if="orderList.length" class="order-info">
            <el-table v-show="status !== 2 && status !== 3 && status !== 4 && status !== 5 && status !== 6" :data="orderList">
                <el-table-column min-width="161" align="center" label="订单号" prop="number"></el-table-column>
                <el-table-column min-width="157" align="center" label="订单状态" prop="status" :formatter="formatStatus"></el-table-column>
                <el-table-column min-width="157" label="用户名" prop="userName"></el-table-column>
                <el-table-column min-width="157" label="手机号" prop="phone"></el-table-column>
                <el-table-column min-width="157" label="地址" prop="address"></el-table-column>
                <el-table-column min-width="216" align="center" label="下单时间" prop="orderTime"></el-table-column>
                <el-table-column min-width="157" align="center" label="实收金额" prop="amount"></el-table-column>
                <el-table-column min-width="275" align="center" label="操作" class-name="operate">
                  <template slot-scope="scope">
                    <button
                     class="btn"
                     v-show="scope.row.status === 4"
                     @click="handleComplete(scope.row.id)">完成</button>
                    <button
                     class="btn"
                     v-show="scope.row.status === 3"
                     @click="handleDelivery(scope.row.id)">派送</button>
                    <button
                     class="btn"
                     v-show="scope.row.status === 2"
                     @click="handleTakeOrder(scope.row.id)">接单</button>
                    <button
                     class="btn cancel"
                     v-show="scope.row.status === 2"
                     @click="handleRejectOrder(scope.row.id)">拒单</button>
                    <button
                     class="btn cancel"
                     v-show="scope.row.status !== 5 && scope.row.status !== 6 && scope.row.status !== 2"
                     @click="handleCancelOrder(scope.row.id)">取消</button>
                    <button
                     class="btn"
                     @click="handleViewDetail(scope.row.id)">查看</button>
                  </template>
                </el-table-column>
            </el-table>
            <el-table v-show="status === 2 || status === 3 || status === 4" :data="orderList">
                <el-table-column min-width="164" align="center" label="订单号" prop="number"></el-table-column>
                <el-table-column min-width="159" label="订单菜品" prop="orderDishes"></el-table-column>
                <el-table-column min-width="159" label="地址" prop="address"></el-table-column>
                <el-table-column min-width="219" align="center" label="预计送达时间" prop="estimatedDeliveryTime"></el-table-column>
                <el-table-column min-width="159" align="center" label="实收金额" prop="amount"></el-table-column>
                <el-table-column min-width="159" align="center" label="备注" prop="remark"></el-table-column>
                <el-table-column min-width="159" align="center" label="餐具数量" prop="tablewareNumber"></el-table-column>
                <el-table-column min-width="259" align="center" label="操作" class-name="operate">
                  <template slot-scope="scope">
                    <button
                     class="btn"
                     v-show="scope.row.status === 4"
                     @click="handleComplete(scope.row.id)">完成</button>
                    <button
                     class="btn"
                     v-show="scope.row.status === 3"
                     @click="handleDelivery(scope.row.id)">派送</button>
                    <button
                     class="btn"
                     v-show="scope.row.status === 2"
                     @click="handleTakeOrder(scope.row.id)">接单</button>
                    <button
                     class="btn cancel"
                     v-show="scope.row.status === 2"
                     @click="handleRejectOrder(scope.row.id)">拒单</button>
                    <button
                     class="btn cancel"
                     v-show="scope.row.status !== 5 && scope.row.status !== 6 && scope.row.status !== 2"
                     @click="handleCancelOrder(scope.row.id)">取消</button>
                    <button
                     class="btn"
                     @click="handleViewDetail(scope.row.id)">查看</button>
                  </template>
                </el-table-column>
            </el-table>
            <el-table v-show="status === 5 || status === 6" :data="orderList">
              <el-table-column min-width="161" align="center" label="订单号" prop="number"></el-table-column>
              <el-table-column min-width="157" label="用户名" prop="userName"></el-table-column>
              <el-table-column min-width="157" label="手机号" prop="phone"></el-table-column>
              <el-table-column min-width="157" label="地址" prop="address"></el-table-column>
              <el-table-column v-if="status === 5" width="216" align="center" label="送达时间" prop="deliveryTime"></el-table-column>
              <el-table-column v-else min-width="216" align="center" label="下单时间" prop="orderTime"></el-table-column>
              <el-table-column v-if="status === 5" width="157" align="center" label="实收金额" prop="amount"></el-table-column>
              <el-table-column v-if="status === 5" min-width="157" align="center" label="备注" prop="remark"></el-table-column>
              <el-table-column v-if="status === 6" min-width="157" align="center" label="取消时间" prop="cancelTime"></el-table-column>
              <el-table-column v-if="status === 6" min-width="157" align="center" label="取消原因" prop="cancelReason"></el-table-column>
              <el-table-column min-width="275" align="center" label="操作" class-name="operate">
                <template slot-scope="scope">
                  <button
                    class="btn"
                    v-show="scope.row.status === 4"
                    @click="handleComplete(scope.row.id)">完成</button>
                  <button
                    class="btn"
                    v-show="scope.row.status === 3"
                    @click="handleDelivery(scope.row.id)">派送</button>
                  <button
                    class="btn"
                    v-show="scope.row.status === 2"
                    @click="handleTakeOrder(scope.row.id)">接单</button>
                  <button
                    class="btn cancel"
                    v-show="scope.row.status === 2"
                    @click="handleRejectOrder(scope.row.id)">拒单</button>
                  <button
                    class="btn cancel"
                    v-show="scope.row.status !== 5 && scope.row.status !== 6 && scope.row.status !== 2"
                    @click="handleCancelOrder(scope.row.id)">取消</button>
                  <button
                    class="btn"
                    @click="handleViewDetail(scope.row.id)">查看</button>
                </template>
              </el-table-column>
            </el-table>
            <div class="paginate">
              <el-pagination
                layout="total, sizes, prev, pager, next, jumper"
                :page-sizes="[10, 20, 30, 40]"
                :total="pageTotal"
                :page-size.sync="pageSize"
                :current-page.sync="page"
                @size-change="getOrder()"
                @current-change="getOrder()"
              ></el-pagination>
            </div>
        </div>
        <div v-else class="order-info">
          <div class="empty">
            <img src="@/assets/search_table_empty.png" alt="">
            <span>这里空空如也~</span>
          </div>
        </div>
    </div>
    <DialogOrderDetail
      @update:dialogVisibleOrder="dialogVisibleOrder = $event"
      :dialogVisibleOrder="dialogVisibleOrder"
      :orderDetails="orderDetails"
      :orderDishDetailList="orderDishDetailList"
      @click="handleBtnClick">
    </DialogOrderDetail>
    <!-- 拒绝原因弹窗 -->
    <el-dialog
     :title="rejectDialogTitle"
     :visible.sync="dialogVisibleReject"
     width="45%">
      <div class="reject-box">
        <div>
          <span>{{ rejectDialogTitle }}：</span>
          <el-select v-model="rejectReason" :placeholder="`请选择${rejectDialogTitle}`">
            <el-option
            v-for="item in rejectReasonList" :key="item.value"
            :label="item.label"
            :value="item.value"></el-option>
          </el-select>
        </div>
        <div v-if="rejectDialogTitle === '拒绝原因' && rejectReason === reject.length">
          <span>原因：</span>
          <el-input v-model="rejectReasonText" max="20" type="textarea" :placeholder="`请填写您${rejectDialogTitle}（限20字内）`"></el-input>
        </div>
        <div v-if="rejectDialogTitle === '取消原因' && rejectReason === cancel.length">
          <span>原因：</span>
          <el-input v-model="rejectReasonText" max="20" type="textarea" :placeholder="`请填写您${rejectDialogTitle}（限20字内）`"></el-input>
        </div>
      </div>
      <template slot="footer">
          <el-button @click="dialogVisibleReject = false">取消</el-button>
          <el-button @click="confirmReject" type="primary">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { formatDate } from '@/utils/formatDate'
import { getOrderStatus } from '@/utils/utils'
import { getOrder, getOrderCount, getOrderDetails, deliveryOrder, rejectOrder, takeOrder, completeOrder, cancelOrder } from '@/api/order'
import OrderStatusNav from '@/components/OrderStatusNav.vue'
import DialogOrderDetail from '@/components/DialogOrderDetail.vue'
export default {
  name: 'OrderIndex',
  components: {
    OrderStatusNav,
    DialogOrderDetail
  },
  data () {
    return {
      // 拒绝原因弹窗数据
      orderId: 0,
      rejectType: '拒单',
      rejectDialogTitle: '拒绝原因',
      dialogVisibleReject: false,
      rejectReason: '',
      rejectReasonText: '',
      rejectReasonList: [],
      reject: [
        { value: 1, label: '订单量较多，暂时无法接单' },
        { value: 2, label: '菜品已销售完，暂时无法接单' },
        { value: 3, label: '餐厅已打洋，暂时无法接单' },
        { value: 4, label: '自定义原因' }
      ],
      cancel: [
        { value: 1, label: '订单数量较多，暂时无法接单' },
        { value: 2, label: '菜品已销售完，暂时无法接单' },
        { value: 3, label: '骑手不足无法配送' },
        { value: 4, label: '客户电话取消' },
        { value: 5, label: '自定义原因' }
      ],
      // 订单详情弹窗数据
      dialogVisibleOrder: false,
      orderDetails: {},
      orderDishDetailList: [],
      orderStatusNav: [
        {
          title: '全部订单',
          status: 0,
          badge: 0
        },
        {
          title: '待接单',
          status: 2,
          badge: 0
        },
        {
          title: '待派送',
          status: 3,
          badge: 0
        },
        {
          title: '派送中',
          status: 4,
          badge: 0
        },
        {
          title: '已完成',
          status: 5,
          badge: 0
        },
        {
          title: '已取消',
          status: 6,
          badge: 0
        }
      ],
      orderDate: '',
      orderList: [],
      // 订单搜索数据
      beginTime: '',
      endTime: '',
      number: '',
      page: 1,
      pageSize: 10,
      pageTotal: 0,
      phone: '',
      status: null
    }
  },
  created () {
    this.getOrder()
    this.getOrderCount()
  },
  methods: {
    getOrderStatus,
    async getOrder () {
      const res = await getOrder({
        beginTime: this.beginTime,
        endTime: this.endTime,
        number: this.number,
        page: this.page,
        pageSize: this.pageSize,
        phone: this.phone,
        status: this.status
      })
      if (res.code === 1) {
        this.orderList = res.data.records
        this.pageTotal = res.data.total
      }
    },
    async getOrderCount () {
      const res = await getOrderCount()
      if (res.code === 1) {
        this.orderStatusNav[1].badge = res.data.toBeConfirmed
        this.orderStatusNav[2].badge = res.data.confirmed
        this.orderStatusNav[3].badge = res.data.deliveryInProgress
      }
    },
    async getOrderDetails (id) {
      const res = await getOrderDetails(id)
      if (res.code === 1) {
        this.orderDetails = res.data
        this.orderDishDetailList = res.data.orderDetailList
      }
    },
    handleSearch () {
      this.getOrder()
    },
    formatStatus (row, column, cellValue, index) {
      return getOrderStatus(cellValue)
    },
    confirmDate (date) {
      this.beginTime = formatDate(date[0])
      this.endTime = formatDate(date[1])
    },
    selectStatus (status) {
      this.status = status
      this.getOrder()
      this.getOrderCount()
    },
    async handleViewDetail (id) {
      await this.getOrderDetails(id)
      this.dialogVisibleOrder = true
    },
    async handleDelivery (id) {
      const res = await deliveryOrder(id)
      if (res.code === 1) {
        this.getOrder()
        this.getOrderCount()
        this.$message.success('操作成功')
      } else {
        this.$message.error(res.msg)
      }
    },
    async handleTakeOrder (id) {
      const res = await takeOrder(id)
      if (res.code === 1) {
        this.getOrder()
        this.getOrderCount()
        this.$message.success('操作成功')
      } else {
        this.$message.error(res.msg)
      }
    },
    async handleComplete (id) {
      const res = await completeOrder(id)
      if (res.code === 1) {
        this.getOrder()
        this.getOrderCount()
        this.$message.success('操作成功')
      } else {
        this.$message.error(res.msg)
      }
    },
    handleCancelOrder (id) {
      this.orderId = id
      this.rejectType = '取消'
      this.rejectDialogTitle = '取消原因'
      this.rejectReasonList = this.cancel
      this.dialogVisibleReject = true
    },
    handleRejectOrder (id) {
      this.orderId = id
      this.rejectType = '拒单'
      this.rejectDialogTitle = '拒绝原因'
      this.rejectReasonList = this.reject
      this.dialogVisibleReject = true
    },
    async confirmReject () {
      const reason = this.rejectReasonList.find(item => item.value === this.rejectReason).label

      let res = null
      if (this.rejectType === '拒单') {
        res = await rejectOrder({
          id: this.orderId,
          rejectionReason: this.rejectReason === this.reject.length ? this.rejectReasonText : reason
        })
      } else if (this.rejectType === '取消') {
        res = await cancelOrder({
          id: this.orderId,
          cancelReason: this.rejectReason === this.cancel.length ? this.rejectReasonText : reason
        })
      }

      if (res.code === 1) {
        this.getOrder()
        this.getOrderCount()
        this.$message.success('操作成功')
      } else {
        this.$message.error(res.msg)
      }
      this.dialogVisibleReject = false
      this.rejectReasonText = ''
      this.rejectReason = ''
    },
    // 订单详情弹窗按钮点击事件处理
    async handleBtnClick (state, id, autoNext) {
      if (state === 0) {
        await this.handleRejectOrder(id)
      } else if (state === 6) {
        await this.handleCancelOrder(id)
      } else if (state === 1) {
        await this.handleTakeOrder(id)
      } else if (state === 2) {
        await this.handleDelivery(id)
      } else if (state === 4) {
        await this.handleComplete(id)
      }

      if (autoNext && state !== 0 && state !== 6) {
        const currentIndex = this.orderList.indexOf(this.orderList.find(item => item.id === id))
        const orderDetails = this.orderList[currentIndex + 1]
        this.orderDetails = orderDetails
        this.orderDishDetailList = orderDetails.orderDetailList
        this.dialogVisibleOrder = false
        setTimeout(() => {
          this.dialogVisibleOrder = true
        }, 500)
      } else {
        this.dialogVisibleOrder = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.order-status-nav {
    max-width: 720px;
    height: 40px;
}

.order-main {
    background-color: #fff;
    padding: 20px;
    margin-top: 20px;

    .head {
        display: flex;
        gap: 20px;
        font-size: 14px;

        ::v-deep .el-date-editor .el-range-separator {
          padding: 0;
        }

        > div {
            display: flex;
            align-items: center;
            gap: 5px;

            span {
                flex-shrink: 0;
            }
        }

        .btn {
            background-color: #333;
            color: #fff;
            border-radius: 5px;
            padding: 0 20px;
            cursor: pointer;
            line-height: 0;
        }
    }

    .order-info {
        width: calc(100% - 5px);
        margin-top: 20px;

        ::v-deep .el-table .has-gutter {
            color: #666;

            th {
                border-top: 1px solid #ebeef5;
            }

            th:first-of-type {
                border-left: 1px solid #ebeef5;
            }

            th:nth-child(8) {
                border-right: 1px solid #ebeef5;
            }
        }

        ::v-deep .el-table .el-table__body-wrapper {
            .el-table__empty-block {
                border-left: 1px solid #ebeef5;
                border-right: 1px solid #ebeef5;
            }

            td {
              color: #333;
            }

            td:first-of-type {
                border-left: 1px solid #ebeef5;
            }

            td:last-of-type {
                border-right: 1px solid #ebeef5;
            }
        }

        ::v-deep .el-table td.operate .cell {
          display: flex;
          justify-content: center;

          .btn {
            display: flex;
            border: 0;
            background-color: transparent;
            color: #419eff;
            margin-right: 20px;
            cursor: pointer;
          }

          .btn::after {
            display: block;
            content: "";
            width: 1px;
            height: 18px;
            background-color: #ebeef5;
            margin-left: 20px;
          }

          .btn:last-of-type::after {
            display: none;
          }

          .btn:last-of-type {
            margin-right: 0;
          }

          .cancel {
            color: #f56c6c;
          }
        }

        .empty {
          text-align: center;
          padding: 50px 0;

          > img {
            width: 238px;
            margin: 0 auto;
            margin-bottom: 5px;
          }

          > span {
            font-size: 14px;
            color: #818693;
          }
        }
    }
}

::v-deep .el-dialog {
  .reject-box {
    padding: 20px 50px;

    > div {
      display: flex;
      align-items: center;
      max-width: 400px;
      margin-bottom: 20px;

      &:last-child {
        margin-bottom: 0;
      }

      span {
        flex: .5;
      }

      > div {
        flex: 2;
      }

      .el-textarea {
        width: auto;
      }
    }
  }
}
</style>
